<?php
/**
 * Created by PhpStorm.
 * User: HP_USER
 * Date: 2018/11/16
 * Time: 14:26
 */
namespace app\admin\controller;

use app\AdminData\PlatformMaterialData;
use app\AdminData\ProxyManageData;
use app\common\Common;

class ProxyManage extends Base
{
    private $sortType = ['asc', 'desc'];

    private $userSort = ['create_time'];
    private $specialProvince = [110000, 120000, 310000, 500000];

    public function _initialize($str = null)
    {
        parent::_initialize($str); // TODO: Change the autogenerated stub
    }

    /**
     * 区域代理列表显示
     * @param int $type
     * @param int $page
     * @param int $pre
     * @param array $sort
     * @param int $key
     * @param int $value
     * @return \think\response\Json
     */
    public function showProxyManageList($type = -1, $page = 1, $pre = 15, $sort = ['create_time' => 'desc'], $key = 0, $value = 0)
    {
        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->userSort, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        if (!in_array($type, [-1, 0, 1, 2])) {
            return json(['code' => $this->f_code, 'msg' => '非法操作']);
        }
        $where = $this->getProxyWhere($key, $value, $type);
        $data = new ProxyManageData();
        $res = $data->showProxyManageList($where, $page, $pre, $sort);
        $total = $data->ProxyManageTotal($where);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'list' => $res,
                'total' => $total
            ]
        ]);
    }

    /**
     * where 拼接
     * @param $key
     * @param $value
     * @param $type
     * @return string
     */
    private function getProxyWhere($key, $value, $type)
    {
        $where = "a.recover_status=0 ";
        switch ($type) {
            case 0:
            case 1:
            case 2:
                $where = " and a.type_lv={$type}";
                break;
            default:
                break;
        }
        if ($key === 0) {
            return $where;
        }
        switch ($key) {
            case 'user_id':
                $where = $where . " and a.user_id='{$value}'";
                break;
            case 'user_tel':
                $where = $where . " and b.user_tel='{$value}'";
                break;
            case 'city_name':
                $where = $where . " and c.name like '%{$value}%'";
                break;
            default:
                break;
        }
        return $where;
    }

    /**
     * 搜索用户信息
     * @param int $key
     * @param int $value
     * @param int $page
     * @param int $pre
     * @param array $sort
     * @return \think\response\Json
     */
    public function searchUserList($key = 0, $value = 0, $page = 1, $pre = 15, $sort = ['create_time' => 'desc'])
    {
        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->userSort, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $where = $this->getUserListWhere($key, $value);
        $data = new ProxyManageData();
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'list' => $data->searchUserList($where, $page, $pre, $sort),
                'total' => Common::total($where, 'drh_user_info a')
            ]
        ]);
    }

    private function getUserListWhere($key, $value)
    {
        $where = "a.recover_status=0";
        if ($key === 0) {
            return $where;
        }
        switch ($key) {
            case 'user_id':
                $where = $where . " and a.id='{$value}'";
                break;
            case 'user_tel':
                $where = $where . " and a.user_tel='{$value}'";
                break;
            case 'user_name':
                $where = $where . " and a.user_name like '%{$value}%'";
                break;
            default:
                break;
        }
        return $where;
    }


    /**
     * 省代
     * @param $type_lv
     * @return bool|\think\response\Json
     */
    public function showProvince($type_lv)
    {
        $proxy_data = new ProxyManageData();
        $res = $proxy_data->getAreaInfo($type_lv);
        switch ($type_lv) {
            case  1://省代
                return json(['code' => $this->t_code, 'msg' => 'ok', 'data' => $this->removalProvince($res, $proxy_data)]);
            case  2://市代
                return json(['code' => $this->t_code, 'msg' => 'ok', 'data' => $res]);
            default :
                return true;
        }
    }

    /**
     * 去除已经代理的省份
     * @param $res
     * @param ProxyManageData $proxy_data
     * @return array
     */
    private function removalProvince($res, ProxyManageData $proxy_data)
    {
        $info = $proxy_data->getProxyAreaInfo(" a.type_lv=1 and a.recover_status=0 ");
        $area = [];
        foreach ($res as $v) {
            $area[$v['name']] = $v['id'];
        }
        $proxy = [];
        foreach ($info as $v) {
            $proxy[$v['name']] = $v['id'];
        }
        $arr = array_diff($area, $proxy);
        $return_arr = [];
        foreach ($arr as $k => $v) {
            $return_arr[] = ['name' => $k, 'id' => $v];
        }
        return $return_arr;
    }

    /**
     * 市代
     * @param $p_id
     * @return \think\response\Json
     */
    public function showMunicipal($p_id)
    {
        if (in_array($p_id, $this->specialProvince)) {
            return json(['code' => $this->t_code, 'msg' => '直辖市没有市代']);
        }
        $proxy_data = new ProxyManageData();
        $res = $proxy_data->getAreaInfo(2, $p_id);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $this->removalMunicipal($p_id, $res, $proxy_data)
        ]);
    }

    /**
     * 获取大区信息
     * @param int $type
     * @return \think\response\Json
     */
    public function showArea($type = 2)
    {
        $proxy_data = new ProxyManageData();
        $data = $proxy_data->getArea();
        if ($type == 1) {
            $p_data = $proxy_data->getProxyArea();
            $data = empty($p_data) ? $data : $this->removalArea($p_data, $data);

        }
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $data
        ]);
    }

    public function removalArea($proxy_data, $data)
    {
        $arr = [];
        foreach ($proxy_data as $k => $v) {
            $arr[] = $v['area_id'];
        }

        foreach ($data as $k => $v) {
            if(in_array($v['id'],$arr)){
                unset($data[$k]);
            }
        }
        return $data;
    }


    /**
     * 去除已经代理的市
     * @param $p_id
     * @param $res
     * @param ProxyManageData $proxy_data
     * @return array
     */
    private function removalMunicipal($p_id, $res, ProxyManageData $proxy_data)
    {
        $info = $proxy_data->getProxyAreaInfo(" b.parent_id={$p_id} and a.recover_status=0 ");
        $area = [];
        foreach ($res as $v) {
            $area[$v['name']] = $v['id'];
        }
        $proxy = [];
        foreach ($info as $v) {
            $proxy[$v['name']] = $v['id'];
        }
        $arr = array_diff($area, $proxy);
        $return_arr = [];
        foreach ($arr as $k => $v) {
            $return_arr[] = ['name' => $k, 'id' => $v];
        }
        return $return_arr;
    }

    /**
     * 代理抬头统计显示
     * @return \think\response\Json
     */
    public function showProxyTitle()
    {
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'province_total' => Common::total("type_lv=1 and recover_status=0", 'drh_proxy'),
                'municipal_total' => Common::total("type_lv=2 and recover_status=0", 'drh_proxy'),
                'area_total' => Common::total("type_lv=0 and recover_status=0", 'drh_proxy'),
            ]
        ]);
    }

    /**
     * 添加区域代理
     * @param $user_id
     * @param $type_id
     * @param $area_id
     * @param $proxy_money
     * @param $msg
     * @return \think\response\Json
     */
    public function addProxyUser($user_id, $type_id, $area_id, $proxy_money, $msg)
    {
        $res = $this->checkProxyUser($user_id, $type_id, $area_id, $proxy_money, $msg);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $proxy_data = new ProxyManageData();
        $time = time();
        $id = $proxy_data->addProxyUser($user_id, $type_id, $area_id, $proxy_money, $time);
        if ($id) {
            return json(['code' => $this->t_code, 'msg' => '添加成功']);
        } else {
            return json(['code' => $this->f_code, 'msg' => '添加失败请稍后在试']);
        }
    }

    private function checkProxyUser($user_id, $type_id, $area_id, $proxy_money, $msg)
    {
        if (!in_array($type_id, [0, 1, 2])) {
            return ['code' => $this->f_code, 'msg' => '区域类别错误'];
        }
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return ['code' => $this->f_code, 'msg' => '不存在'];
        };
        //用户是否重复
        $res = Common::getTableValue('drh_proxy', 'id', ['recover_status', 'user_id'], [0, $user_id]);
        if (!empty($res)) {
            return ['code' => $this->f_code, 'msg' => '请勿重复代理'];
        }
        //区域是否重复
        $res = Common::getTableValue('drh_proxy', 'id', ['recover_status', 'area_id'], [0, $area_id]);
        if (!empty($res)) {
            return ['code' => $this->f_code, 'msg' => '请勿重复代理'];
        }

        if (Common::checkTableFields('china_area', 'id', $area_id) == $this->f_code) {
            return ['code' => $this->f_code, 'msg' => '不存在'];
        };
        if (!is_numeric($proxy_money) || $proxy_money < 0 || strlen($proxy_money) > 10) {
            return ['code' => $this->f_code, 'msg' => '输入金额错误'];
        }
        if (mb_strlen($msg) > 2000) {
            return ['code' => $this->f_code, 'msg' => '消息内容过长请控制在2000字内'];
        }
        return ['code' => $this->t_code];
    }

    /**
     * 平台数据代理抬头
     * @param $area_id
     * @return \think\response\Json
     * @throws \Exception
     */
    public function showProxyManageTitle($area_id)
    {
        $res = Common::getTableValue('drh_proxy', ['area_id', 'total_money', 'proxy_money', 'type_lv'], ['area_id'], [$area_id]);
        if (empty($res)) {
            return json(['code' => $this->f_code, 'msg' => '没有该区域代理']);
        }
        $area_name = Common::getTableValue('china_area', 'name', ['id'], [$res['area_id']]);
        $total_money = round($res['total_money'] - $res['total_money'] * 0.02);
        $data = new ProxyManageData();
        $where = "(a.type_status=4 or a.type_status=6) ";
        $shop_where = "b.total >=20 and b.status=1 ";
        $order_where = " a.pay_status >= 2 ";
        switch ($res['type_lv']) {
            case 0:
                $where .= " and d.area_id={$area_id}";
                $admin_order_money = ($res['total_money'] / config('region'));//订单总收入扣除了微信手续费
                $shop_where .= " and a.area_id={$area_id} ";
                $drh_proxy = $res['proxy_money'] * 0.9;//大区代理收入
                $province_money = ($this->provinceProxyMoney($area_id, $data)) * 0.9;
                $proxy_money = $drh_proxy + $province_money;
                $order_where .= " and b.area_id={$area_id}";
                break;
            case 1:
                $where .= " and d.province_id={$area_id}";
                $admin_order_money = ($res['total_money'] / config('province'));//订单总收入扣除了微信手续费
                $shop_where .= " and a.province_id={$area_id} ";
                $drh_proxy = $res['proxy_money'] * 0.9;//省代收入
                $city_money = ($this->cityProxyMoney($area_id, $data)) * 0.9;//市代收入
                $proxy_money = $drh_proxy + $city_money;
                $order_where .= " and b.province_id={$area_id}";
                break;
            case 2:
                $where .= " and d.city_id={$area_id}";
                $admin_order_money = ($res['total_money'] / config('city'));//订单总收入扣除了微信手续费
                $shop_where .= " and a.city_id={$area_id} ";
                $drh_proxy = $res['proxy_money'] * 0.9;//区代理收入
                $proxy_money = $drh_proxy;
                $order_where .= " and b.city_id={$area_id}";
                break;
            default:
                throw new \Exception("服务器错误");
        }
        $return_money = $this->weChatReturnMoney($where, $data);
        $shop_total = $this->shopNumberTotal($shop_where, $data);
        $order_money_total = $this->getAreaOrderMoneyTotal($order_where, $data);
        $order_money_weChat = ($order_money_total['price'] + $order_money_total['freight_price']) * 0.006;//微信手续费
        $shop_money = $shop_total * 10000;//推荐商户纯收入
        //平台管理费-(用户代理+商户代理)  +商家年费+ (代理收入-推荐人分佣)-微信手续费
        $admin_money = ($admin_order_money - $return_money) + $shop_money + $proxy_money - $order_money_weChat;
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'area_name' => $area_name,
                'proxy_money' => $total_money,
                'lv' => $res['type_lv'],
                'admin_money' => $admin_money
            ]
        ]);
    }

    //分销获得金钱 (用户和商户)
    private function weChatReturnMoney($where, ProxyManageData $data)
    {
        $res = $data->weChatReturnMoney($where);
        return $res;
    }

    //商户个数
    private function shopNumberTotal($where, ProxyManageData $data)
    {
        $res = $data->shopNumberTotal($where);
        return $res;
    }

    /**
     * 获取代理省下面市的所有代理收入
     * @param $area_id
     * @param ProxyManageData $data
     * @return int|mixed
     */
    private function cityProxyMoney($area_id, ProxyManageData $data)
    {
        $id = $data->getCityId($area_id);
        $city_id = [];
        foreach ($id as $k => $v) {
            $city_id[] = $v['id'];
        }
        $arr_string = join(',', $city_id);
        $where = " area_id in({$arr_string})";
        $res = $data->cityProxyMoney($where);
        return $res;
    }

    /**
     * 省+市获得代理金额
     * @param $area_id
     * @param ProxyManageData $data
     * @return mixed
     */
    private function provinceProxyMoney($area_id, ProxyManageData $data)
    {
        $id = config('area_id');
        $province_id = $id[$area_id];
        $arr_string = join(',', $province_id);
        $where = " area_id in({$arr_string})";
        $res = $data->provinceProxyMoney($where);
        if ($res['area_id'] == 0) {
            return $res['proxy_money'];
        } else {
            $arr_id = explode(',', $res['area_id']);
            $city_money = 0;
            foreach ($arr_id as $k => $v) {
                $city_money += $this->cityProxyMoney($v, $data);
            }
        }
        return $res['proxy_money'] + $city_money;
    }

    public function areaInfo($area_id)
    {
        $res = Common::getTableValue('drh_proxy', 'user_id', ['area_id'], [$area_id]);
        if (empty($res)) {
            return json(['code' => $this->f_code, 'msg' => '没有该区域代理']);
        }
        $data = new ProxyManageData();
        $res = $data->getProxyUserInfo($res);
        return json(['code' => $this->t_code, 'msg' => 'OK', 'data' => $res]);
    }

    /**
     * 平台服务费
     * @param $area_id
     * @return \think\response\Json
     * @throws \Exception
     */
    public function platformServiceMoney($area_id)
    {
        $res = Common::getTableValue('drh_proxy', ['area_id', 'total_money', 'proxy_money', 'type_lv'], ['area_id'], [$area_id]);
        if (empty($res)) {
            return json(['code' => $this->f_code, 'msg' => '没有该区域代理']);
        }
        $shop_where = "b.total >=20 and b.status=1 ";
        switch ($res['type_lv']) {
            case 0:
                $shop_where .= " and a.area_id={$area_id} ";
                break;
            case 1:
                $shop_where .= " and a.province_id={$area_id} ";
                break;
            case 2:
                $shop_where .= " and a.city_id={$area_id} ";
                break;
            default:
                throw new \Exception("服务器错误");
        }
        $data = new ProxyManageData();
        $shop_total = $this->shopNumberTotal($shop_where, $data);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'shop_money' => $shop_total * 17800,
                'admin_money' => $shop_total * 10000,
                'recommend_money' => $shop_total * 7800
            ]
        ]);
    }

    /**
     * 平台平台管理费
     * @param $area_id
     * @return \think\response\Json
     * @throws \Exception
     */
    public function platformManagementMoney($area_id)
    {
        $res = Common::getTableValue('drh_proxy', ['area_id', 'total_money', 'proxy_money', 'type_lv'], ['area_id'], [$area_id]);
        if (empty($res)) {
            return json(['code' => $this->f_code, 'msg' => '没有该区域代理']);
        }
        $where = "(a.type_status=4 or a.type_status=6) ";
        $order_where = " a.pay_status >= 2 ";
        switch ($res['type_lv']) {
            case 0:
                $where .= " and d.area_id={$area_id}";
                $admin_order_money = $res['total_money'] / config('region');//平台管理费
                $order_where .= " and b.area_id={$area_id}";
                break;
            case 1:
                $where .= " and d.province_id={$area_id}";
                $admin_order_money = $res['total_money'] / config('province');//平台管理费
                $order_where .= " and b.province_id={$area_id}";
                break;
            case 2:
                $where .= " and d.city_id={$area_id}";
                $admin_order_money = $res['total_money'] / config('city');//平台管理费
                $order_where .= " and b.city_id={$area_id}";
                break;
            default:
                throw new \Exception("服务器错误");
        }
        $data = new ProxyManageData();
        $return_money = $this->weChatReturnMoney($where, $data);
        $order_money_total = $this->getAreaOrderMoneyTotal($order_where, $data);
        $order_money_weChat = ($order_money_total['price'] + $order_money_total['freight_price']) * 0.006;//微信手续费
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'platform_money' => $order_money_total['total_price'] + $order_money_total['goods_freight'],
                'platform_management_money' => $admin_order_money,
                'weChat_money' => $order_money_weChat,
                'return_money' => $return_money,
            ]
        ]);
    }

    private function getAreaOrderMoneyTotal($where, ProxyManageData $data)
    {
        return $data->getAreaOrderMoneyTotal($where);
    }

    /**
     * 盈利及分红
     * @param int $area_id
     * @return \think\response\Json
     * @throws \Exception
     */
    public function areaDividend($area_id)
    {
        $res = Common::getTableValue('drh_proxy', ['area_id', 'total_money', 'proxy_money', 'type_lv'], ['area_id'], [$area_id]);
        if (empty($res)) {
            return json(['code' => $this->f_code, 'msg' => '没有该区域代理']);
        }
        $total_money = round($res['total_money']);
        $recommend_money = round($res['total_money'] * 0.02);
        $data = new ProxyManageData();
        switch ($res['type_lv']) {
            case 0:
                $admin_order_money = ($res['total_money'] / config('region'));//带去代理平台订单总收入
                //扣除省代 市代分红
                $dividend_money = ($this->getProvinceDividendMoney($area_id, $data)) * 0.9;
                break;
            case 1:
                $admin_order_money = ($res['total_money'] / config('province'));//省代平台订单总收入
                //市代分红
                $dividend_money = $this->getCityDividendMoney($area_id, $data);
                break;
            case 2:
                $admin_order_money = ($res['total_money'] / config('city'));//市代平台订单总收入
                $dividend_money = 0;
                break;
            default:
                throw new \Exception("服务器错误");
        }
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'area_proxy_money' => $total_money,
                'recommend_money' => $recommend_money,
                'admin_money' => $admin_order_money - $res['total_money'] - $dividend_money
            ]
        ]);
    }

    private function getCityDividendMoney($area_id, ProxyManageData $data)
    {
        $id = $data->getCityId($area_id);
        $city_id = [];
        foreach ($id as $k => $v) {
            $city_id[] = $v['id'];
        }
        $arr_string = join(',', $city_id);
        $where = " area_id in({$arr_string})";
        $res = $data->cityTotalMoneyMoney($where);
        return $res;
    }

    /**
     * 盈利及分红
     * @param $area_id
     * @param ProxyManageData $data
     * @return mixed
     */
    private function getProvinceDividendMoney($area_id, ProxyManageData $data)
    {
        $id = config('area_id');
        $province_id = $id[$area_id];
        $arr_string = join(',', $province_id);
        $where = " area_id in({$arr_string})";
        $res = $data->provinceTotalMoneyMoney($where);
        if ($res['area_id'] == 0) {
            return $res['total_money'];
        } else {
            $arr_id = explode(',', $res['area_id']);
            $city_money = 0;
            foreach ($arr_id as $k => $v) {
                $city_money += $this->getCityDividendMoney($v, $data);
            }
        }
        return $res['total_money'] + $city_money;
    }

}